<?php

namespace app\admin\controller;

use app\model\AdminLogModel;
use support\Request;
use support\Response;
use Exception;
use app\model\AdminModel;

class LogController
{
    /**
     * 获取日志列表
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        try {
            $current = (int)$request->get('current', 1);
            $pageSize = (int)$request->get('pageSize', 10);
            
            $query = AdminLogModel::query();
            
            
            if ($action = $request->get('action')) {
                $query->where('action', 'like', "%{$action}%");
            }

            if ($adminName = $request->get('admin_name')) {
                $query->whereHas('admin', function ($query) use ($adminName) {
                    $query->where('username', 'like', "%{$adminName}%");
                });
            }   
            
            $total = $query->count();
            $list = $query->orderBy('id', 'desc')
                ->offset(($current - 1) * $pageSize)
                ->limit($pageSize)
                ->get();

            $log_action = config('admin.log_action');

            foreach ($list as &$item) {
                $item['created_at'] = date('Y-m-d H:i:s', $item->created_at);
                $item['action_label'] = !empty($log_action[$item->action]) ? $log_action[$item->action] :  $item->action;

                $admin = AdminModel::find($item->admin_id);
                $item['admin_name'] = $admin->username;
            }
                
            return json([
                'data' => [
                    'list' => $list,
                    'total' => $total
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 删除日志
     * @param Request $request
     * @return Response
     */
    public function delete(Request $request): Response
    {
        try {
            $id = $request->post('id');
            
            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $log = AdminLogModel::find($id);
            if (!$log) {
                throw new Exception('日志不存在');
            }

            if (!$log->delete()) {
                throw new Exception('删除失败');
            }

            return json([
                'data' => null,
                'msg' => '删除成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
}
